<?php

declare(strict_types=1);

namespace App\Utils\Control;

use Hyperf\Coroutine\Coroutine;
use Hyperf\HttpServer\Router\Dispatched;
use Psr\Http\Message\ServerRequestInterface;

class ActionUtil
{
    private static string $prefix = 'App\Controller\\';

    protected array $actions = [];// 控制器信息

    protected static array $instance = [];

    public static function getInstance(): ActionUtil
    {
        //协程id
        $coroutine_id = Coroutine::id();
        if (empty(self::$instance[$coroutine_id])) {
            self::$instance[$coroutine_id] = new self();

            Coroutine::defer(function () use ($coroutine_id) {
                unset(self::$instance[$coroutine_id]);
            });
        }
        return self::$instance[$coroutine_id];
    }

    /**
     * 获取当前路由地址
     * @param ServerRequestInterface $request
     * @param string $project
     * @return array
     */
    public function actions(ServerRequestInterface $request, string $project = 'Api'): array
    {
        $action     = $request->getAttribute(Dispatched::class)->handler->callback ?? [];
        $controller = str_replace(self::$prefix.$project . '\\', '', $action[0] ?? '');
        $controller = str_replace('\\', '/', $controller);
        if (!empty($action[1])) {
            $this->actions['controller'] = $controller ?? 'CommonController';
            $this->actions['action']     = $action[1];
        } else {
            $this->actions['controller'] = 'CommonController';
            $this->actions['action']     = 'common';
        }
        return $this->actions;
    }

    public function get()
    {
        return $this->actions;
    }
}